package cn.com.smart.framework.aspectj;

import cn.com.smart.common.utils.StringUtils;
import cn.com.smart.framework.aspectj.lang.annotation.DataSource;
import cn.com.smart.framework.aspectj.lang.annotation.WriteAll;
import cn.com.smart.framework.datasource.DynamicDataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 多数据源处理
 *
 */
@Aspect
@Order(2)
@Component
public class WriteAllAspect {
    protected Logger log = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(cn.com.smart.framework.aspectj.lang.annotation.WriteAll)")
    public void waPointCut() {

    }

    @Around("waPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        WriteAll writeAll = method.getAnnotation(WriteAll.class);
        if (StringUtils.isNullOrEmpty(writeAll)) {
            //判断类上面是否有注解
            if(method.getDeclaringClass().isAnnotationPresent(WriteAll.class)) {
                writeAll = method.getDeclaringClass().getDeclaredAnnotation(WriteAll.class);
                System.out.println("写入注解");
            }
        }
        return point.proceed();
//        if (StringUtils.isNotNull(writeAll)) {
//            log.info("写入多个数据源：", writeAll.value());
//            DynamicDataSourceContextHolder.setDataSourceType(writeAll.value());
//        }
//
//        try {
//            return point.proceed();
//        } finally {
//            // 销毁数据源 在执行方法之后
//            DynamicDataSourceContextHolder.clearDataSourceType();
//        }
    }
}
